package com.example.myapplication.utils;

import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    private final Context context;
    private final Thread.UncaughtExceptionHandler defaultUEH;

    public static final String TAG = "MyExceptionHandler";

    public MyExceptionHandler(Context context) {
        this.context = context;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        // Capture the exception details
        String errorLog = Log.getStackTraceString(throwable);

        // Save the error log to a file
     //   saveErrorLogToFile(errorLog);

        QZXTools.logD(TAG,"错误信息 =" + throwable.getMessage());

        // Call the default handler if needed (this will terminate the app)
        defaultUEH.uncaughtException(thread, throwable);
    }

    private void saveErrorLogToFile(String errorLog) {
        try {
            File logFile = new File(context.getExternalFilesDir(null), "error_log.txt");
            FileWriter writer = new FileWriter(logFile, true);
            writer.append(errorLog);
            writer.append('\n');
            writer.close();
        } catch (IOException e) {
            Log.e("MyExceptionHandler", "Error writing to log file", e);
        }
    }
}

